package com.hxk.juc.thread.single;

/**
 * 懒汉式单例模式如果不加synchronized在多线程下会成为不是单例模式
 */
public class SingleCase1 {

    private static SingleCase1 instance = null;

    private SingleCase1(){
        System.out.println(Thread.currentThread().getName()+"\t 我是SingleCase的私有构造方法");
    }

    public synchronized static SingleCase1 getInstance(){
        if(instance == null){
            instance = new SingleCase1();
        }
        return instance;
    }

    public static void main(String[] args) {
        singleThread();
        manyThread();
    }

    /**
     * 在单线程模式下不synchronized是没有一点问题的
     */
    private static void singleThread(){
        System.out.println(SingleCase1.getInstance() == SingleCase1.getInstance());
        System.out.println(SingleCase1.getInstance() == SingleCase1.getInstance());
        System.out.println(SingleCase1.getInstance() == SingleCase1.getInstance());
    }

    /**
     * 在多线程环境下不synchronized会出现SingleCase对象被实例化多次的情况
     */
    public static void manyThread(){
        for (int i = 1; i <= 10; i++) {
            new Thread(()->{
                SingleCase1.getInstance();
            },String.valueOf(i)).start();
        }
    }
}
